﻿CREATE PROCEDURE [maint].[AddDevice]
@DeviceName [sysname], @DeviceDoP int = 1, @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @RC int ,@ERROR int
	SET @RC = 0
	
	--Get device path
	DECLARE @BackupPath varchar(128)
	SET @BackupPath = config.GetInstanceSetting(N'BackupPath')
	IF (@BackupPath IS NULL)
		BEGIN
			RAISERROR('Insert DBADb config value for ''BackupPath''',16,1)
			SET @ERROR = @@ERROR
			GOTO ERROR_HANDLER
		END	

	IF(@OutputDiagnostics = 1)
		PRINT 'Backup Path: ' + @BackupPath;

	DECLARE @DeviceExtension nchar(4);
	SET @DeviceExtension = maint.GetDeviceExtension(@DeviceName);
	
	DECLARE @DevicePath nvarchar(256)
	SET @DevicePath = @BackupPath +
		(CASE
			WHEN RIGHT(@BackupPath,1) = N'\' THEN N''
			ELSE N'\'
		END)
		+ REPLACE(@DeviceName,'CURRENT','0')
		+ @DeviceExtension;

	IF(@OutputDiagnostics = 1)
		PRINT 'Device Path: ' + @DevicePath;
		PRINT 'Degree of parallelism: ' + CAST(@DeviceDoP AS nvarchar);

	--drop existing device(including parallel devices)
	DECLARE DEVICE_GROUP CURSOR FAST_FORWARD FOR(
		SELECT [name] FROM master.dbo.sysdevices
		WHERE ([name] LIKE @DeviceName + N'%') --ignore parallel index no.
	);
	DECLARE @PhysicalDeviceName sysname;
	OPEN DEVICE_GROUP;
	FETCH NEXT FROM DEVICE_GROUP INTO @PhysicalDeviceName;
	WHILE(@@FETCH_STATUS = 0)
	BEGIN
		BEGIN TRY
			EXEC sp_dropdevice @PhysicalDeviceName;
		END TRY
		BEGIN CATCH
			PRINT N'Failed to drop device: ' + @PhysicalDeviceName;
		END CATCH

		FETCH NEXT FROM DEVICE_GROUP INTO @PhysicalDeviceName;
	END
	CLOSE DEVICE_GROUP;
	DEALLOCATE DEVICE_GROUP;

	DECLARE @ParallelDeviceNo int = 1;
	WHILE(@ParallelDeviceNo <= @DeviceDoP)
	BEGIN
		DECLARE @ParallelDeviceName sysname, @ParallelDevicePath nvarchar(260);
		SET @ParallelDeviceName = @DeviceName + '.' + CAST(@ParallelDeviceNo AS nvarchar);
		SET @ParallelDevicePath = @DevicePath + CAST(@ParallelDeviceNo AS nvarchar);

		EXEC @RC = sp_addumpdevice N'disk', @ParallelDeviceName, @ParallelDevicePath;
		SET @ERROR = @@ERROR;
		IF(@ERROR <> 0)
		OR(@RC <> 0)
			BEGIN
				RAISERROR('Failed to add backup device %s',16,1,@ParallelDeviceName);
				GOTO ERROR_HANDLER;
			END

		SET @ParallelDeviceNo = @ParallelDeviceNo + 1;
	END
	
	GOTO EXIT_PROC
	
ERROR_HANDLER:
	IF(@RC = 0)
		SET @RC = @ERROR

EXIT_PROC:
	RETURN(@RC)
END